package com.kaily.imagelib.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class BitmapUtils {


    /**
     * 绘制合成图片
     *
     * @param firstBitmap
     * @param secondBitmap
     * @return
     */
    public static Bitmap mergeAdBitmap(Bitmap firstBitmap, Bitmap secondBitmap, int x, int y) {
        if (firstBitmap == null || secondBitmap == null) {
            return null;
        }
        int sourceBitmapHeight = firstBitmap.getHeight();
        int sourceBitmapWidth = firstBitmap.getWidth();
        Bitmap.Config config = firstBitmap.getConfig();
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        Bitmap shareBitmap = Bitmap.createBitmap(sourceBitmapWidth, sourceBitmapHeight,
                config);
        Canvas canvas = new Canvas(shareBitmap);
        canvas.drawBitmap(firstBitmap, 0, 0, paint);
        canvas.drawBitmap(secondBitmap, x, y, null);
        return shareBitmap;
    }

    public static Bitmap getBitmapFormUrl(String imagePath) {
        return getBitmapFormUrl(imagePath, false);
    }

    /**
     * 根据网络地址获取图片bitmap
     */
    public static Bitmap getBitmapFormUrl(String imagePath, boolean isThrowOutOfMemoryError) {
        if (TextUtils.isEmpty(imagePath)) {
            return null;
        }

        Bitmap bitmap = null;
        URL url = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        try {

            URLConnection urlConnection;
            url = new URL(imagePath);
            trustAllHosts();
            urlConnection = url.openConnection();

            try {
                if ("https".equals(url.getProtocol().toLowerCase())) {
                    ((HttpsURLConnection) urlConnection).setHostnameVerifier(DO_NOT_VERIFY);
                }
            } catch (Exception e) {

            }


            is = urlConnection.getInputStream();
            bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            return bitmap;
        } catch (OutOfMemoryError outOfMemoryError) {
            if (isThrowOutOfMemoryError) {
                throw outOfMemoryError;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (is != null) {
                    is.close();
                }

            } catch (Exception e) {

            }

        }

    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }    //将所有验证的结果都设为true
    };

    /**
     * 不检查任何证书
     */
    private static void trustAllHosts() {
        final String tag = "trustAllHosts";
        // 创建信任管理器
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                Log.i(tag, "checkClientTrusted");
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                Log.i(tag, "checkServerTrusted");
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param options   参数
     * @param reqWidth  目标的宽度
     * @param reqHeight 目标的高度
     * @return
     * @description 计算图片的压缩比率
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * @param src
     * @param dstWidth
     * @param dstHeight
     * @return
     * @description 通过传入的bitmap，进行压缩，得到符合标准的bitmap
     */
    private static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight, int inSampleSize) {
        if (inSampleSize % 2 == 0) {
            return src;
        }
        // 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响，我们这里是缩小图片，所以直接设置为false
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        // 如果没有缩放，那么不回收
        if (src != dst) {
            // 释放Bitmap的native像素数组
            src.recycle();
        }
        return dst;
    }

    /**
     * 将图片放大或缩小到指定尺寸
     */
    public static Bitmap resizeImage(Bitmap source, int dstWidth, int dstHeight) {
        if (source == null) {
            return null;
        }
        return Bitmap.createScaledBitmap(source, dstWidth, dstHeight, true);
    }

    /**
     * 将图片剪裁为圆形
     */
    public static Bitmap createCircleImage(Bitmap source) {
        if (source == null) {
            return null;
        }

        int length = Math.min(source.getWidth(), source.getHeight());
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(target);
        canvas.drawCircle(source.getWidth() / 2, source.getHeight() / 2, length / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        return target;
    }


    public static File saveBitmap(Bitmap bitmap, String dir, String fileName) {

        //参数校验
        if (bitmap == null || TextUtils.isEmpty(dir) || TextUtils.isEmpty(fileName)) {
            return null;
        }

        File filePic;
        FileOutputStream fos = null;
        try {

            filePic = new File(dir, fileName);
            if (!filePic.exists()) {
                File parentFile = filePic.getParentFile();
                if (parentFile != null && !parentFile.exists()) {
                    parentFile.mkdirs();
                }

                if (parentFile != null && parentFile.exists()) {
                    filePic.createNewFile();
                }

            }

            fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {

            }

        }

        return filePic;
    }


    /**
     * 图片缩放适配
     *
     * @param activity
     * @param resourceBitmap
     * @return
     */
    public static Bitmap scaleImage(final Activity activity, Bitmap resourceBitmap) {
        if (activity == null || resourceBitmap == null) {
            return resourceBitmap;
        }

        try {
// 获取屏幕的高宽
            Point outSize = new Point();
            activity.getWindow().getWindowManager().getDefaultDisplay().getSize(outSize);


            // 使用图片的缩放比例计算将要放大的图片的高度
            int bitmapScaledHeight = Math.round(resourceBitmap.getHeight() * outSize.x * 1.0f / resourceBitmap.getWidth());

            // 以屏幕的宽度为基准，如果图片的宽度比屏幕宽，则等比缩小，如果窄，则放大
            final Bitmap scaledBitmap = Bitmap.createScaledBitmap(resourceBitmap, outSize.x, bitmapScaledHeight, false);

            int viewHeight = outSize.y;

            // 计算将要裁剪的图片的顶部以及底部的便宜量
            int offset = (scaledBitmap.getHeight() - viewHeight) / 2;
            if (offset <= 0) {
                return scaledBitmap;
            }
            // 对图片以中心进行裁剪，裁剪出的图片就是非常适合做引导页的图片了
            Bitmap finallyBitmap = Bitmap.createBitmap(scaledBitmap, 0, offset, scaledBitmap.getWidth(),
                    scaledBitmap.getHeight() - offset * 2);
            return finallyBitmap;
        } catch (Exception e) {
            return resourceBitmap;
        }
    }

    public static Bitmap getLoacalBitmap(String url) {
        if (!TextUtils.isEmpty(url)) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }

    /**
     * 按照指定宽高缩放
     *
     * @param origin
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap scaleBitmap(Bitmap origin, int newWidth, int newHeight) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        return newBM;
    }

    /**
     * 按照比例缩放
     *
     * @param origin
     * @param ratio
     * @return
     */
    public static Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        return newBM;
    }

    public static Bitmap createCircleImage(Bitmap source, int size) {
        if (source == null || size <= 0) {
            return null;
        }
        source = zoomBitmap(source, size, size);
        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(target);
        canvas.drawCircle(size / 2, size / 2, size / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        return target;
    }

    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidth = (float) width / (float) w;
        float scaleHeight = (float) height / (float) h;
        int x = 0;
        int y = 0;
        float scaleSize = 1.0f;
        Bitmap newbmp;
        Matrix matrix = new Matrix();
        if (scaleWidth >= 1.0f && scaleHeight >= 1.0f) {
            scaleSize = Math.max((float) w / (float) width, (float) h / (float) height);
        } else if (scaleWidth <= 1.0f && scaleHeight <= 1.0f) {
            scaleSize = Math.max((float) w / (float) width, (float) h / (float) height);
        } else if (scaleWidth <= 1.0f && scaleHeight >= 1.0f) {
            scaleSize = (float) w / (float) width;
        } else if (scaleWidth >= 1.0f && scaleHeight <= 1.0f) {
            scaleSize = (float) h / (float) height;
        }
        matrix.postScale(scaleSize, scaleSize);
        try {
            //先缩放
            newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            //在裁剪
            width = newbmp.getWidth();
            height = newbmp.getHeight();
            x = (width - w) / 2;
            y = (height - h) / 2;
            x = x < 0 ? 0 : x;
            y = y < 0 ? 0 : y;
            w = Math.min(w, width);
            h = Math.min(h, height);
            newbmp = Bitmap.createBitmap(newbmp, x, y, w, h, null, false);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return newbmp;
    }
}
